package com.ambimmort.ucagent.modules.webservice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Cacher implements Runnable {

    private static Cacher instance = null;

    public static Cacher getInstance(){
        if(instance == null){
            instance = new Cacher();
            new Thread(instance).start();
        }
        return instance;
    }

    public Cacher() {

    }

    private List<Thing> msgs = new ArrayList<Thing>();

    private ExecutorService service = Executors.newFixedThreadPool(1);

    public List<Thing> getMsgs() {
        return msgs;
    }

    public void setMsgs(List<Thing> msgs) {
        this.msgs = msgs;
    }



    public long getTimeLimit() {
        return timeLimit;
    }

    public void setTimeLimit(long timeLimit) {
        this.timeLimit = timeLimit;
    }

    public int getCacheLimit() {
        return cacheLimit;
    }

    public void setCacheLimit(int cacheLimit) {
        this.cacheLimit = cacheLimit;
    }

    /**
     * timeLimit 缓存超时时间，默认1分钟
     */
    private long timeLimit = 5000;

    private int cacheLimit = 5000;

    private long lastProcessTime = System.currentTimeMillis();


    public void addTing(Thing msg) {
        System.out.println("Add "+msg+" to Cacher. Cacher.size="+msgs.size());
        msgs.add(msg);
        if (msgs.size() >= cacheLimit) {
            process();
        }
    }


    public void run() {
        while (true) {
            try{
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //检查是否该处理
//                System.out.println("Check or not? "+((System.currentTimeMillis() - lastProcessTime) >= timeLimit));
                if ((System.currentTimeMillis() - lastProcessTime) >= timeLimit) {
                    process();
                    lastProcessTime = System.currentTimeMillis();
                }
            }catch(Throwable t){
                t.printStackTrace();
            }

        }
    }

    private synchronized void process() {
        try {
            if ((this.msgs)!=null&&(this.msgs.size() != 0)) {
                final List<Thing> task = this.msgs;
                this.msgs = new ArrayList<Thing>();
                Worker worker = new Worker();
                worker.setMsgs(task);
                service.submit(worker);
            }
        }catch (Throwable throwable){
            throwable.printStackTrace();
        }

    }

}

